package com.kefu.boss.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.google.common.collect.Maps;
import com.kefu.boss.mapper.BossUserMapper;
import com.kefu.boss.model.BossMenu;
import com.kefu.boss.model.BossUser;
import com.kefu.boss.userdetails.KefuUserDetailsService;
import com.kefu.common.context.KefuContext;
import com.kefu.common.util.StreamUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class BossSelfService {
    PasswordEncoder passwordEncoder;
    @Resource
    protected BossUserMapper bossUserMapper;
    @Resource
    protected BossRoleService bossRoleService;
    @Autowired
    protected KefuUserDetailsService userDetailsService;
    @Resource
    protected RedisTemplate<String, BossMenu> redisTemplate;
    @Autowired
    protected MessageSourceAccessor messageSourceAccessor;

    @Value("${kefu.sys.maxRetryTimes:3}")
    int maxRetryTimes;

    public BossUser findSelfInfo() {
        BossUser bossUser = bossUserMapper.selectById(KefuContext.getUid());
        if (Objects.nonNull(bossUser)) {
            bossUser.setRoleList(bossRoleService.getByUserId(bossUser.getUserId()));
        }
        return bossUser;
    }

    // 从redis中获取用户菜单，如果没有则从数据库中获取
    public List<Tree<String>> selfMenuList(){
        List<BossMenu> list = userDetailsService.findUserMenuById(KefuContext.getUid());
        List<TreeNode<String>> nodeList = CollUtil.newArrayList();
        StreamUtil.stream(list).forEach(item -> {
            TreeNode<String> node = new TreeNode<>(item.getId(), item.getParentId(), item.getName(), item.getWeight());
            Map<String, Object> extra = Maps.newHashMap();
            extra.put("path", item.getPath());
            extra.put("component", item.getComponent());
            extra.put("redirect", item.getRedirect());
            extra.put("icon", item.getIcon());
            extra.put("type", item.getType());
            extra.put("hidden", true);
            node.setExtra(extra);
            nodeList.add(node);
        });
        return TreeUtil.build(nodeList, "0");
    }
}
